package eom.example.elasticsearch.controller;

import bom.example.common.common.Results;
import com.alibaba.fastjson.JSONObject;
import eom.example.elasticsearch.domain.Student;
import eom.example.elasticsearch.service.StudentService;
import eom.example.elasticsearch.utils.ElasticSearchUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author X.I.O
 * @title: EsController
 * @projectName springboot
 * @description: TODO
 * @date 2021/11/2 12:13
 */
@Api(tags = {"es服务"})
@RestController
@RequestMapping("/es")
public class EsController {

    @Autowired
    private ElasticSearchUtils elasticSearchUtils;

    @Autowired
    private StudentService studentService;


    @ApiOperation("创建按索引")
    @PostMapping("/createIndexName")
    public JSONObject createIndexNameController(String indexName) throws Exception{
        elasticSearchUtils.createIndex(indexName);
        return Results.success();
    }


    @ApiOperation("判断索引是否存在")
    @PostMapping("/exist")
    public JSONObject existIndexName(String indexName,String id) throws Exception{
        boolean falg=elasticSearchUtils.existIndexName(indexName,id);
        String msg=falg?"存在":"不存在";
        return Results.success(indexName+":"+msg);
    }

    @ApiOperation("获取所有测试数据")
    @PostMapping("getall")
    public JSONObject getAllDataController(){
        List<Student> students=studentService.list();
        return Results.success(students);
    }


    @ApiOperation("添加单个数据")
    @PostMapping("/addOne")
    public JSONObject addOneController(String indexName,Integer id) throws Exception{
        Student student=studentService.getById(id);
        elasticSearchUtils.addDocument(student,indexName);
        return Results.success();
    }

    @ApiOperation("批量添加所有数据")
    @PostMapping("addAll")
    public JSONObject addAllController(String indexName) throws Exception {
        List<Student> students=studentService.list();
        elasticSearchUtils.addList(students,indexName);
        return Results.success();
    }


    @ApiOperation("es的根据名称搜索")
    @PostMapping("/search")
    public JSONObject searchController(String indexName,String keyword) throws Exception{
        List<Student> students=elasticSearchUtils.searchList(indexName,"stuName",keyword,Student.class);
        return Results.success(students);
    }

    @ApiOperation("es根据id搜索")
    @PostMapping("/getOne")
    public JSONObject getOneController(String indexName,String idValue) throws Exception{
        Student student=elasticSearchUtils.getDocumentById(indexName,idValue,Student.class);
        return Results.success(student);
    }

    @ApiOperation("es根据id删除")
    @PostMapping("delete")
    public JSONObject deleteController(@ApiParam("索引名称") @RequestParam("indexName")String indexName,
                                       @ApiParam("id值")@RequestParam("idValue") String idValue) throws Exception{
        elasticSearchUtils.deleteById(indexName,idValue);
        return Results.success();
    }

    @ApiOperation("es根据id更新")
    @PostMapping("update/{indexName}")
    public JSONObject updateController(@RequestBody Student student,@PathVariable("indexName")String indexName) throws Exception{
        elasticSearchUtils.updateDocumentById(student,indexName);
        return Results.success();
    }

    @ApiOperation("stu的es全搜索")
    @PostMapping("getAll")
    public JSONObject searchAllController(@ApiParam("页码")@RequestParam(value = "page",defaultValue = "1")Integer page,
                                          @ApiParam("条数")@RequestParam(value = "size",defaultValue = "10")Integer size,
                                          @ApiParam("索引名称")@RequestParam(value = "indexName")String indexName,
                                          @ApiParam("搜索词")@RequestParam(value = "keyword",required = false) String keyword) throws Exception{
        //创建搜索的builder
        SearchSourceBuilder builder=new SearchSourceBuilder();
        //创建条件构造器
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        if(StringUtils.isNotBlank(keyword)){
            MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders
                    .matchPhraseQuery("stuNote", keyword);
            boolQueryBuilder.should(matchPhraseQueryBuilder);
        }

        if(StringUtils.isNotBlank(keyword)){
            MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("stuAddress", keyword);
            boolQueryBuilder.should(matchQuery);
        }

        if(StringUtils.isNotBlank(keyword)){
            MatchQueryBuilder matchQuery_1 = QueryBuilders.matchQuery("stuName", keyword);
            boolQueryBuilder.should(matchQuery_1);

            MatchQueryBuilder matchQuery_2 = QueryBuilders.matchQuery("stuMobile", keyword);
            boolQueryBuilder.should(matchQuery_2);
        }

        //开始查询
        builder.query(boolQueryBuilder);
        //从第几页
        builder.from(page-1);
        //每页多少条
        builder.size(size);
        //获取需要的列和不需要的列
        builder.fetchSource(new String[]{"id","stuNote", "stuMobile","stuAddress","createDate","stuName"}, new String[]{});
        // 设置排序规则
        builder.sort("createDate", SortOrder.DESC);
        Map<String, Object> map=elasticSearchUtils.searchListObject(indexName,builder,Student.class);
        return Results.success(map);
    }



}
